package com.suxin.http.request;

import com.suxin.exception.utils.TryCatchExceptionUtils;
import com.suxin.http.model.RequestHttpEntity;
import com.suxin.http.response.handler.ResultRestResponseHandler;

import java.net.URI;
import java.util.concurrent.CompletableFuture;

/**
 * @author Tang
 * @classname DefaultAsyncHttpClientRequest
 * @description [ 异步 ]
 * @date 2023/3/5 20:33
 */
public class DefaultAsyncHttpClientRequest implements AsyncHttpClientRequest{

    private final JdkHttpClientRequest clientRequest;

    public DefaultAsyncHttpClientRequest(JdkHttpClientRequest clientRequest) {
        this.clientRequest = clientRequest;
    }

    @Override
    public <T> void execute(URI uri, String method, RequestHttpEntity requestHttpEntity, Callback<T> callback) throws Exception {
        CompletableFuture.supplyAsync(() -> {
            try {
                return clientRequest.execute(uri, method, requestHttpEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }).thenApply((response) -> {
            final ResultRestResponseHandler<T> responseHandler = new ResultRestResponseHandler<>();
            return TryCatchExceptionUtils.exceptionReturn(ResultRestResponseHandler::handlerResponse,responseHandler, response);
        }).whenComplete((v,e) -> v.ifPresent(callback::onReceive));
    }
}
